package com.example.kotlineventtracker.util

import android.content.Context
import android.util.Log
import com.example.kotlineventtracker.model.ApiService
import com.example.kotlineventtracker.model.EventInfoRequestBody
import com.example.kotlineventtracker.model.InfoResponse
import com.example.kotlineventtracker.model.PageEventRequestBody
import com.example.kotlineventtracker.model.PointResponse
import com.google.gson.Gson
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class EventRepository private constructor(
    context: Context
) {

    private var token: String? = null  // token 存储在实例中
    private lateinit var api: ApiService

    companion object {
        @Volatile
        private var INSTANCE: EventRepository? = null

        // 获取 EventRepository 的单例实例
        fun getInstance(context: Context): EventRepository {
            return INSTANCE ?: synchronized(this) {
                val instance = INSTANCE ?: EventRepository(context)
                INSTANCE = instance
                instance
            }
        }
    }

    // 初始化代码
    init {
        val loggingInterceptor = HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        }

        val noCacheInterceptor = Interceptor { chain ->
            val originalRequest = chain.request()
            val newRequest = originalRequest.newBuilder().apply {
                header("Cache-Control", "no-cache")
            }.build()
            chain.proceed(newRequest)
        }

        val tokenInterceptor = Interceptor { chain ->
            val originalRequest = chain.request()
            val newRequestBuilder = originalRequest.newBuilder().apply {
                token?.let {
                    Log.d("TokenInterceptor", "Adding token: $it")
                    addHeader("token", "bearer_$it")
                } ?: run {
                    Log.d("TokenInterceptor", "Token is null!")
                }
            }
            val newRequest = newRequestBuilder.build()
            return@Interceptor chain.proceed(newRequest)
        }

        val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .addInterceptor(noCacheInterceptor)
            .addInterceptor(tokenInterceptor)
            .build()

        val retrofit = Retrofit.Builder()
            .baseUrl("https://event-tracking-server.hellobike.cn/")
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build()

        api = retrofit.create(ApiService::class.java)
    }

    // 设置 token
    fun setToken(newToken: String) {
        token = newToken
    }

    // 获取页面事件的函数
    fun fetchPageEvents(
        request: PageEventRequestBody,
        onSuccess: (PointResponse?) -> Unit,
        onFailure: (Throwable) -> Unit
    ) {
        val requestBody = RequestBody.create(
            "application/json; charset=utf-8".toMediaTypeOrNull(),
            Gson().toJson(request)
        )
        val call = api.getPageEvents(token ?: "", requestBody)

        call.enqueue(object : Callback<PointResponse> {
            override fun onResponse(call: Call<PointResponse>, response: Response<PointResponse>) {
                if (response.isSuccessful) {
                    val body = response.body()
                    onSuccess(body)
                } else {
                    onFailure(RuntimeException("Request was not successful"))
                }
            }

            override fun onFailure(call: Call<PointResponse>, throwable: Throwable) {
                onFailure(throwable)
            }
        })
    }

    // 获取事件信息的函数
    fun fetchEventInfo(
        request: EventInfoRequestBody,
        onSuccess: (InfoResponse?) -> Unit,
        onFailure: (Throwable) -> Unit
    ) {
        val requestBody = RequestBody.create(
            "application/json; charset=utf-8".toMediaTypeOrNull(),
            Gson().toJson(request)
        )
        val call = api.getEventInfo(token ?: "", requestBody)

        call.enqueue(object : Callback<InfoResponse> {
            override fun onResponse(call: Call<InfoResponse>, response: Response<InfoResponse>) {
                if (response.isSuccessful) {
                    val body = response.body()
                    onSuccess(body)
                } else {
                    onFailure(RuntimeException("Request was not successful"))
                }
            }

            override fun onFailure(call: Call<InfoResponse>, throwable: Throwable) {
                onFailure(throwable)
            }
        })
    }
}
